#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/3 20:53
# @Author : diyhome
# @Site : https://github.com/diyhome
# @File : TAnswer.py
# @Software: PyCharm

# 问题的答案
import json
import time
from proxy import ProxyIP


class TAnswer:
    # 文章标题
    page_title = ""
    def __init__(self, url, sleep_time=0):
        self.url = url
        self.__sleep_time = sleep_time
    '''
    @description: 获取所有的回答
    @param {type} offset:json请求的页数
    @return: List:[[Author, [content], hot], ................]
    '''    
    def get_json(self, offset=0):
        # 构造请求url
        question_id = self.url.split('/')[-1]
        json_url = 'https://www.zhihu.com/api/v4/questions/{0}/answers?include=data[*].is_normal,admin_closed_comment,reward_info,is_collapsed,annotation_action,annotation_detail,collapse_reason,is_sticky,collapsed_by,suggest_edit,comment_count,can_comment,content,editable_content,voteup_count,reshipment_settings,comment_permission,created_time,updated_time,review_info,relevant_info,question.detail,excerpt,relationship.is_authorized,is_author,voting,is_thanked,is_nothelp,is_labeled,is_recognized;data[].mark_infos[].url;data[].author.follower_count,badge[].topics&limit=5&offset={1}&platform=desktop&sort_by=default'.format(question_id, offset)

        FinalData = []
        is_end = False   # 因为json上面自带一个属性判断是否到了最后
        record_title = False
        proxy = ProxyIP()
        while not is_end:
            json_raw = proxy.getHtml(json_url)
            while not json_raw:
                json_raw = proxy.getHtml(json_url)
            data = json.loads(json_raw)
            if not record_title:
                self.page_title = data['data'][0]['question']['title']
                record_title = True
            for index in range(len(data['data'])):
                FinalData.append(self.__data_filter(data['data'][index]))
            is_end = data['paging']['is_end']
            json_url = data['paging']['next']  # 提取下一页的链接
            print(json_url)
            time.sleep(self.__sleep_time)
        return FinalData
    '''
    @description: 私有方法:提取有用的信息
    @param {type} 原生json数据
    @return: 一个子列
    '''    
    def __data_filter(self, raw_data):
        tmp_data = []
        tmp_data.append(raw_data['author']['name'])
        tmp_data.append(raw_data['content'])
        tmp_data.append(raw_data['voteup_count'])
        return tmp_data

if __name__ == '__main__':
    url = "https://www.zhihu.com/question/339011506"
    ta = TAnswer(url)
    tmp = ta.get_json()
    print(tmp)